package com.dd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.reggie.common.CustomException;
import com.dd.reggie.common.R;
import com.dd.reggie.dto.DishDto;
import com.dd.reggie.entity.Dish;
import com.dd.reggie.entity.DishFlavor;
import com.dd.reggie.service.CategoryService;
import com.dd.reggie.service.DishFlavorService;
import com.dd.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

        @Autowired
        private DishService dishService;

        @Autowired
        private DishFlavorService dishFlavorService;

        @Autowired
        private CategoryService categoryService;

        /**
         * 新增菜品，需要操作两个表dish与dish_flovor
         * @param dishDto
         * @return
         */
        @PostMapping
        public R<String> save(@RequestBody DishDto dishDto){

                log.info("DishDto:{}", dishDto);

                dishService.saveWithFlavor(dishDto);

                return R.success("新增成功");
                }

        @GetMapping("/page")
        public R<Page> page(int page, int pageSize, String name){

                //Dish中不存在应该要返回的属性字段categoryName,需要用Dto扩展实体的属性
                //在category中查询categoryName
                Page<Dish> pageInfo = new Page(page, pageSize);

                LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.like(name != null, Dish::getName, name);
                queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
                dishService.page(pageInfo, queryWrapper);

                //Page<Dish>能够分页查询到值，但是dishDto不可以，此时使用对象拷贝
                //先将其余部分拷贝，再单独处理实体部分
                //copyProperties,拷贝类，复制对象
                Page<DishDto> dishDtoPage = new Page(page, pageSize);
                //复制除去records的部分
                BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

                List<Dish> records = pageInfo.getRecords();
                //使用stream流将records与categoryName复制到新Lis中去
                List<DishDto> list =  records.stream().map((item) -> {
                Long categoryId = item.getCategoryId();
                String categoryName = categoryService.getById(categoryId).getName();
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(item, dishDto);
                dishDto.setCategoryName(categoryName);

                return dishDto;
                }).collect(Collectors.toList());
                //collect(Collectors.toList()) 相当于将每次返回的dishDto组装成List,先分散，再重组

                //将新的records放进去
                dishDtoPage.setRecords(list);

                return R.success(dishDtoPage);
                }

        /**
         * 删除菜品，同时删除对应的口味
         * @param ids
         * @return
         */
        @DeleteMapping
        public R<String> delete(@RequestParam List<Long> ids) {
                log.info("{}", ids.size());
                dishService.removeWithDish(ids);

                return R.success("删除成功");
                }

        //    注意用{}方式接收status1
        @PostMapping("/status/{status1}")
        public R<String> status(@PathVariable int status1, @RequestParam List<Long> ids){

                //判断所选菜品是否均为启用/禁用状态
        //        select count(*) from dish where id in ids and status = 1/0
                LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(Dish::getId, ids).eq(Dish::getStatus, status1);
                int count = dishService.count(queryWrapper);

                //抛出异常
                if(count != 0){
                String msg = new String();
                if(status1 == 1){
                msg = "所选菜品中存在状态为启售状态的菜品";
                }
                else{
                msg = "所选菜品中存在状态为停售状态的菜品";
                }
                throw new CustomException(msg);
                }

                //否则，修改状态
                //updateById 方法一般是根据传入的对象中设置了值的字段来进行更新操作，未设置值的字段在数据库中会保持原有值不变。
                for(Long id : ids){
                Dish dish = new Dish();
                dish.setId(id);
                dish.setStatus(status1);
                dishService.updateById(dish);
                }

                return R.success("状态修改成功");
                }

//        @GetMapping("/list")
//        //使用Dish接收数据，id，name，均可装入
//        //参数种类可能有多种时，使用类接收
//        public R<List<Dish>> list(Dish dish){
//
//                log.info(dish.toString());
//
//                //select * from dish where CategoryId = categoryId
//                LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//
//                queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId()).orderByDesc(Dish::getUpdateTime);
//
//                queryWrapper.like(dish.getName() != null, Dish::getName, dish.getName());
//
//                queryWrapper.orderByAsc(Dish::getSort);
//
//                //只查status=1的菜品
//                queryWrapper.eq(Dish::getStatus, 1);
//
//                List<Dish> list = dishService.list(queryWrapper);
//
//                return R.success(list);
//        }

        @GetMapping("/list")
        public R<List<DishDto>> list(Dish dish){

                //select * from dish where CategoryId = categoryId
                LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId()).orderByDesc(Dish::getUpdateTime);
                queryWrapper.like(dish.getName() != null, Dish::getName, dish.getName());
                queryWrapper.orderByAsc(Dish::getSort);

                //只查status=1的菜品
                queryWrapper.eq(Dish::getStatus, 1);

                List<Dish> list = dishService.list(queryWrapper);

                List<DishDto> dishDtoes = list.stream().map((item) -> {
                        DishDto dto = new DishDto();
                        BeanUtils.copyProperties(item, dto);
                        LambdaQueryWrapper<DishFlavor> flavorWrapper = new LambdaQueryWrapper<>();
                        flavorWrapper.eq(DishFlavor::getDishId, item.getId());
                        dto.setFlavors(dishFlavorService.list(flavorWrapper));
                        return dto;
                }).collect(Collectors.toList());

                return R.success(dishDtoes);
        }


}
